package com.sunfeng.netty.heima.demo;

import com.sunfeng.netty.heima.demo.message.LoginRequestMessage;
import com.sunfeng.netty.heima.demo.protocol.MessageCodec;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LoggingHandler;

/**
 * @ClassName TestMessageCodec
 * @Description   共享的handler  @Sharable   充分考虑了线程安全
 *                编解码器 一般是不能加@Sharable
 * @Author 孙峰
 * @Date 2022/10/28 17:14
 */
public class TestMessageCodec {
    public static void main(String[] args) throws Exception {
        EmbeddedChannel channel = new EmbeddedChannel(
                new LoggingHandler(),
                //帧的最大长度,length字段的偏移量,length字段的长度,添加到length字段值的补偿值 0,从解码帧中剥离的第一个字节数
                new LengthFieldBasedFrameDecoder(1024, 12, 4, 0, 0),
                new MessageCodec());

        // 测试编码方法是可以的
        LoginRequestMessage message = new LoginRequestMessage("sunfeng", "123456");
       // channel.writeOutbound(message);

        ByteBuf buffer = Unpooled.buffer();
        new MessageCodec().encode(null, message, buffer);
        // 测试半包
        ByteBuf b1 = buffer.slice(0, 100);
        ByteBuf b2 = buffer.slice(100, buffer.readableBytes() - 100);
        b1.retain();
        // 测试入栈
        channel.writeInbound(b1);
        channel.writeInbound(b2);
    }
}
